// 全局变量
let currentPlayerId = null;

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 根据当前页面执行不同的初始化
    const currentPage = window.location.pathname.split('/').pop();
    
    if (currentPage === 'index.html' || currentPage === '') {
        initHomePage();
    } else if (currentPage === 'player.html') {
        initPlayerPage();
    } else if (currentPage === 'admin.html') {
        initAdminPage();
    }
});

// 初始化首页
function initHomePage() {
    displayPlayerCards();
}

// 初始化球员详情页
function initPlayerPage() {
    // 从URL获取球员ID
    const urlParams = new URLSearchParams(window.location.search);
    const playerId = parseInt(urlParams.get('id'));
    
    if (playerId) {
        displayPlayerDetails(playerId);
    } else {
        // 如果没有ID参数，重定向到首页
        window.location.href = 'index.html';
    }
}

// 初始化管理页面
function initAdminPage() {
    displayPlayerList();
    setupAdminEventListeners();
}

// 在首页显示球员卡片
function displayPlayerCards() {
    const container = document.getElementById('player-cards-container');
    if (!container) return;
    
    container.innerHTML = '';
    
    players.forEach(player => {
        const card = document.createElement('div');
        card.className = 'player-card';
        card.dataset.id = player.id;
        
        card.innerHTML = `
            <div class="player-image">
                <img src="${player.image}" alt="${player.name}">
            </div>
            <div class="player-info">
                <h3>${player.name} <span class="player-number">#${player.number}</span></h3>
                <span class="player-position">${player.position}</span>
                <p>年龄: ${player.age}</p>
                <p>国籍: ${player.nationality}</p>
            </div>
        `;
        
        card.addEventListener('click', function() {
            window.location.href = `player.html?id=${player.id}`;
        });
        
        container.appendChild(card);
    });
}

// 显示球员详情
function displayPlayerDetails(playerId) {
    const container = document.getElementById('player-details');
    if (!container) return;
    
    const player = players.find(p => p.id === playerId);
    
    if (!player) {
        container.innerHTML = '<p>未找到该球员信息</p>';
        return;
    }
    
    container.innerHTML = `
        <div class="player-header">
            <div class="player-header-image">
                <img src="${player.image}" alt="${player.name}">
            </div>
            <div class="player-header-info">
                <h2><span class="player-number-large">#${player.number}</span> ${player.name}</h2>
                <span class="player-position-large">${player.position}</span>
                <p>年龄: ${player.age}</p>
                <p>国籍: ${player.nationality}</p>
            </div>
        </div>
        
        <div class="player-bio">
            <h3>球员简介</h3>
            <p>${player.description}</p>
        </div>
        
        <div class="player-stats">
            <h3>能力值</h3>
            <div class="stats-container">
                <div class="stat-item">
                    <div class="stat-value">${player.stats.pace}</div>
                    <div class="stat-label">速度</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${player.stats.shooting}</div>
                    <div class="stat-label">射门</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${player.stats.passing}</div>
                    <div class="stat-label">传球</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${player.stats.dribbling}</div>
                    <div class="stat-label">盘带</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${player.stats.defending}</div>
                    <div class="stat-label">防守</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${player.stats.physical}</div>
                    <div class="stat-label">身体素质</div>
                </div>
            </div>
        </div>
        
        <a href="index.html" class="back-button">返回首页</a>
    `;
}

// 在管理页面显示球员列表
function displayPlayerList() {
    const container = document.getElementById('player-list');
    if (!container) return;
    
    container.innerHTML = '';
    
    players.forEach(player => {
        const item = document.createElement('div');
        item.className = 'player-list-item';
        item.dataset.id = player.id;
        
        item.innerHTML = `
            <div class="player-list-image">
                <img src="${player.image}" alt="${player.name}">
            </div>
            <div class="player-list-info">
                <h4>${player.name} #${player.number}</h4>
                <p>${player.position}</p>
            </div>
            <div class="player-list-actions">
                <button class="edit-btn" data-id="${player.id}"><i class="fas fa-edit"></i></button>
                <button class="delete-btn" data-id="${player.id}"><i class="fas fa-trash"></i></button>
            </div>
        `;
        
        container.appendChild(item);
    });
    
    // 添加编辑和删除按钮的事件监听
    document.querySelectorAll('.edit-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const playerId = parseInt(this.dataset.id);
            openEditForm(playerId);
        });
    });
    
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const playerId = parseInt(this.dataset.id);
            openDeleteConfirmation(playerId);
        });
    });
}

// 设置管理页面的事件监听
function setupAdminEventListeners() {
    // 添加球员按钮
    const addPlayerBtn = document.getElementById('add-player-btn');
    if (addPlayerBtn) {
        addPlayerBtn.addEventListener('click', function() {
            const form = document.getElementById('add-player-form');
            form.style.display = 'block';
            document.getElementById('player-form').reset();
            currentPlayerId = null;
        });
    }
    
    // 取消添加按钮
    const cancelAddBtn = document.getElementById('cancel-add');
    if (cancelAddBtn) {
        cancelAddBtn.addEventListener('click', function() {
            document.getElementById('add-player-form').style.display = 'none';
        });
    }
    
    // 表单提交
    const playerForm = document.getElementById('player-form');
    if (playerForm) {
        playerForm.addEventListener('submit', function(e) {
            e.preventDefault();
            savePlayerData();
        });
    }
    
    // 更换俱乐部徽章按钮
    const changeLogoBtn = document.getElementById('change-logo-btn');
    const logoUpload = document.getElementById('logo-upload');
    
    if (changeLogoBtn && logoUpload) {
        changeLogoBtn.addEventListener('click', function() {
            logoUpload.click();
        });
        
        logoUpload.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    clubLogo = e.target.result;
                    updateLogoDisplay();
                    saveData();
                    showNotification('俱乐部徽章已更新', 'success');
                };
                
                reader.readAsDataURL(this.files[0]);
            }
        });
    }
    
    // 创建编辑表单覆盖层
    createEditFormOverlay();
    createDeleteConfirmDialog();
}

// 创建编辑表单覆盖层
function createEditFormOverlay() {
    const overlay = document.createElement('div');
    overlay.className = 'edit-form-overlay';
    overlay.id = 'edit-form-overlay';
    
    overlay.innerHTML = `
        <div class="edit-form-container">
            <span class="close-form" id="close-edit-form">&times;</span>
            <h3>编辑球员</h3>
            <form id="edit-player-form">
                <div class="form-group">
                    <label for="edit-player-name">姓名:</label>
                    <input type="text" id="edit-player-name" required>
                </div>
                <div class="form-group">
                    <label for="edit-player-number">球衣号码:</label>
                    <input type="number" id="edit-player-number" required min="1" max="99">
                </div>
                <div class="form-group">
                    <label for="edit-player-position">位置:</label>
                    <select id="edit-player-position" required>
                        <option value="门将">门将</option>
                        <option value="后卫">后卫</option>
                        <option value="中场">中场</option>
                        <option value="前锋">前锋</option>
                    </select>
                </div>
                <div class="form-group">
                    <label for="edit-player-age">年龄:</label>
                    <input type="number" id="edit-player-age" required min="16" max="45">
                </div>
                <div class="form-group">
                    <label for="edit-player-nationality">国籍:</label>
                    <input type="text" id="edit-player-nationality" required>
                </div>
                <div class="form-group">
                    <label for="edit-player-description">简介:</label>
                    <textarea id="edit-player-description" rows="4" required></textarea>
                </div>
                <div class="form-group">
                    <label>能力值:</label>
                    <div class="stats-inputs">
                        <div class="stat-input">
                            <label for="edit-player-pace">速度:</label>
                            <input type="number" id="edit-player-pace" required min="1" max="99">
                        </div>
                        <div class="stat-input">
                            <label for="edit-player-shooting">射门:</label>
                            <input type="number" id="edit-player-shooting" required min="1" max="99">
                        </div>
                        <div class="stat-input">
                            <label for="edit-player-passing">传球:</label>
                            <input type="number" id="edit-player-passing" required min="1" max="99">
                        </div>
                        <div class="stat-input">
                            <label for="edit-player-dribbling">盘带:</label>
                            <input type="number" id="edit-player-dribbling" required min="1" max="99">
                        </div>
                        <div class="stat-input">
                            <label for="edit-player-defending">防守:</label>
                            <input type="number" id="edit-player-defending" required min="1" max="99">
                        </div>
                        <div class="stat-input">
                            <label for="edit-player-physical">身体素质:</label>
                            <input type="number" id="edit-player-physical" required min="1" max="99">
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <label for="edit-player-image">球员照片:</label>
                    <input type="file" id="edit-player-image" accept="image/*">
                </div>
                <div class="form-buttons">
                    <button type="submit" class="btn primary-btn">保存</button>
                    <button type="button" id="cancel-edit" class="btn secondary-btn">取消</button>
                </div>
            </form>
        </div>
    `;
    
    document.body.appendChild(overlay);
    
    // 添加关闭按钮事件
    document.getElementById('close-edit-form').addEventListener('click', function() {
        document.getElementById('edit-form-overlay').style.display = 'none';
    });
    
    document.getElementById('cancel-edit').addEventListener('click', function() {
        document.getElementById('edit-form-overlay').style.display = 'none';
    });
    
    // 添加表单提交事件
    document.getElementById('edit-player-form').addEventListener('submit', function(e) {
        e.preventDefault();
        updatePlayerData();
    });
}

// 创建删除确认对话框
function createDeleteConfirmDialog() {
    const dialog = document.createElement('div');
    dialog.className = 'confirm-dialog';
    dialog.id = 'delete-confirm-dialog';
    
    dialog.innerHTML = `
        <div class="confirm-box">
            <h3>确认删除</h3>
            <p>您确定要删除这名球员吗？此操作无法撤销。</p>
            <div class="confirm-buttons">
                <button id="confirm-delete-btn" class="btn confirm-delete">删除</button>
                <button id="cancel-delete-btn" class="btn cancel-delete">取消</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(dialog);
    
    // 添加按钮事件
    document.getElementById('cancel-delete-btn').addEventListener('click', function() {
        document.getElementById('delete-confirm-dialog').style.display = 'none';
    });
    
    document.getElementById('confirm-delete-btn').addEventListener('click', function() {
        deletePlayer(currentPlayerId);
        document.getElementById('delete-confirm-dialog').style.display = 'none';
    });
}

// 打开编辑表单
function openEditForm(playerId) {
    currentPlayerId = playerId;
    const player = players.find(p => p.id === playerId);
    
    if (!player) return;
    
    // 填充表单数据
    document.getElementById('edit-player-name').value = player.name;
    document.getElementById('edit-player-number').value = player.number;
    document.getElementById('edit-player-position').value = player.position;
    document.getElementById('edit-player-age').value = player.age;
    document.getElementById('edit-player-nationality').value = player.nationality;
    document.getElementById('edit-player-description').value = player.description;
    document.getElementById('edit-player-pace').value = player.stats.pace;
    document.getElementById('edit-player-shooting').value = player.stats.shooting;
    document.getElementById('edit-player-passing').value = player.stats.passing;
    document.getElementById('edit-player-dribbling').value = player.stats.dribbling;
    document.getElementById('edit-player-defending').value = player.stats.defending;
    document.getElementById('edit-player-physical').value = player.stats.physical;
    
    // 显示表单
    document.getElementById('edit-form-overlay').style.display = 'flex';
}

// 打开删除确认对话框
function openDeleteConfirmation(playerId) {
    currentPlayerId = playerId;
    document.getElementById('delete-confirm-dialog').style.display = 'flex';
}

// 保存新球员数据
function savePlayerData() {
    const name = document.getElementById('player-name').value;
    const number = parseInt(document.getElementById('player-number').value);
    const position = document.getElementById('player-position').value;
    const age = parseInt(document.getElementById('player-age').value);
    const nationality = document.getElementById('player-nationality').value;
    const description = document.getElementById('player-description').value;
    const pace = parseInt(document.getElementById('player-pace').value);
    const shooting = parseInt(document.getElementById('player-shooting').value);
    const passing = parseInt(document.getElementById('player-passing').value);
    const dribbling = parseInt(document.getElementById('player-dribbling').value);
    const defending = parseInt(document.getElementById('player-defending').value);
    const physical = parseInt(document.getElementById('player-physical').value);
    
    const imageInput = document.getElementById('player-image');
    let imagePromise;
    
    if (imageInput.files && imageInput.files[0]) {
        imagePromise = new Promise((resolve) => {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                resolve(e.target.result);
            };
            
            reader.readAsDataURL(imageInput.files[0]);
        });
    } else {
        imagePromise = Promise.resolve('https://via.placeholder.com/500');
    }
    
    imagePromise.then((imageData) => {
        // 创建新球员对象
        const newPlayer = {
            id: players.length > 0 ? Math.max(...players.map(p => p.id)) + 1 : 1,
            name,
            number,
            position,
            age,
            nationality,
            description,
            image: imageData,
            stats: {
                pace,
                shooting,
                passing,
                dribbling,
                defending,
                physical
            }
        };
        
        // 添加到球员数组
        players.push(newPlayer);
        
        // 保存数据
        saveData();
        
        // 更新显示
        displayPlayerList();
        
        // 隐藏表单
        document.getElementById('add-player-form').style.display = 'none';
        
        // 显示成功通知
        showNotification('球员添加成功', 'success');
    });
}

// 更新球员数据
function updatePlayerData() {
    const name = document.getElementById('edit-player-name').value;
    const number = parseInt(document.getElementById('edit-player-number').value);
    const position = document.getElementById('edit-player-position').value;
    const age = parseInt(document.getElementById('edit-player-age').value);
    const nationality = document.getElementById('edit-player-nationality').value;
    const description = document.getElementById('edit-player-description').value;
    const pace = parseInt(document.getElementById('edit-player-pace').value);
    const shooting = parseInt(document.getElementById('edit-player-shooting').value);
    const passing = parseInt(document.getElementById('edit-player-passing').value);
    const dribbling = parseInt(document.getElementById('edit-player-dribbling').value);
    const defending = parseInt(document.getElementById('edit-player-defending').value);
    const physical = parseInt(document.getElementById('edit-player-physical').value);
    
    const imageInput = document.getElementById('edit-player-image');
    let imagePromise;
    
    if (imageInput.files && imageInput.files[0]) {
        imagePromise = new Promise((resolve) => {
            const reader = new FileReader();
            
            reader.onload = function(e) {
                resolve(e.target.result);
            };
            
            reader.readAsDataURL(imageInput.files[0]);
        });
    } else {
        // 保持原有图片
        const player = players.find(p => p.id === currentPlayerId);
        imagePromise = Promise.resolve(player.image);
    }
    
    imagePromise.then((imageData) => {
        // 查找并更新球员
        const playerIndex = players.findIndex(p => p.id === currentPlayerId);
        
        if (playerIndex !== -1) {
            players[playerIndex] = {
                ...players[playerIndex],
                name,
                number,
                position,
                age,
                nationality,
                description,
                image: imageData,
                stats: {
                    pace,
                    shooting,
                    passing,
                    dribbling,
                    defending,
                    physical
                }
            };
            
            // 保存数据
            saveData();
            
            // 更新显示
            displayPlayerList();
            
            // 隐藏表单
            document.getElementById('edit-form-overlay').style.display = 'none';
            
            // 显示成功通知
            showNotification('球员信息已更新', 'success');
        }
    });
}

// 删除球员
function deletePlayer(playerId) {
    const playerIndex = players.findIndex(p => p.id === playerId);
    
    if (playerIndex !== -1) {
        players.splice(playerIndex, 1);
        
        // 保存数据
        saveData();
        
        // 更新显示
        displayPlayerList();
        
        // 显示成功通知
        showNotification('球员已删除', 'success');
    }
}

// 显示通知
function showNotification(message, type) {
    // 检查是否已存在通知元素
    let notification = document.querySelector('.notification');
    
    if (!notification) {
        notification = document.createElement('div');
        notification.className = 'notification';
        document.body.appendChild(notification);
    }
    
    // 设置通知内容和类型
    notification.textContent = message;
    notification.className = `notification ${type}`;
    
    // 显示通知
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 3秒后隐藏通知
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}